package com.example.backend.repository;

import com.example.backend.domain.entity.TicketFollow;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 工单关注Repository
 */
@Repository
public interface TicketFollowRepository extends JpaRepository<TicketFollow, Long> {

    /**
     * 根据工单ID和用户ID查找关注记录
     */
    Optional<TicketFollow> findByTicketIdAndUserId(Long ticketId, Long userId);

    /**
     * 根据用户ID查找关注的工单
     */
    Page<TicketFollow> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);

    /**
     * 根据工单ID查找关注用户
     */
    List<TicketFollow> findByTicketIdOrderByCreatedAtAsc(Long ticketId);

    /**
     * 统计工单关注数量
     */
    @Query("SELECT COUNT(tf) FROM TicketFollow tf WHERE tf.ticket.id = :ticketId")
    Long countByTicketId(@Param("ticketId") Long ticketId);

    /**
     * 统计用户关注数量
     */
    @Query("SELECT COUNT(tf) FROM TicketFollow tf WHERE tf.user.id = :userId")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 根据关注类型查找
     */
    List<TicketFollow> findByTicketIdAndFollowType(Long ticketId, String followType);

    /**
     * 查找启用了通知的关注记录
     */
    List<TicketFollow> findByTicketIdAndNotificationEnabledTrue(Long ticketId);

    /**
     * 删除用户的关注记录
     */
    void deleteByTicketIdAndUserId(Long ticketId, Long userId);

    /**
     * 批量删除关注记录
     */
    void deleteByTicketIdIn(List<Long> ticketIds);
}
